﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Quartz;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TransformerManager.Shared.Servers;

namespace TransformerManager.API.Quartz.Jobs
{
    [DisallowConcurrentExecution]
    public class DeleteOpLogsJob : IJob
    {
        private readonly IOperationLogService _operationLogService;
        private readonly IConfiguration _configuration;
        private readonly ILogger<DeleteOpLogsJob> _logger;
        public DeleteOpLogsJob(
            IOperationLogService operationLogService, 
            IConfiguration configuration,
            ILogger<DeleteOpLogsJob> logger)
        {
            _operationLogService = operationLogService;
            _configuration = configuration;
            _logger = logger;
        }

        public async Task Execute(IJobExecutionContext context)
        {

            var logTotalNum = await _operationLogService.GetOperationLogsTotalNumAsync();

            //await Task.Run(() =>
            //{
            //    Console.WriteLine($"当前数据库中操作记录为{logTotalNum}-{DateTime.UtcNow}");
            //});

            var thresholdValue = int.Parse(_configuration["Quartz:DelOpearationLogsNumStartFrom"]);
            if (logTotalNum > thresholdValue)
            {
                var delNum = logTotalNum - thresholdValue;
                _operationLogService.DeleteOperationLogsAsync(delNum);

                var isSucceed = await _operationLogService.SaveChangesAsync();

                // 删除操作后进行LOG记录
                if(isSucceed)
                {
                    _logger.LogInformation($"【成功】当前的用户操作记录数量为{logTotalNum}条，用户操作记录已超设定值{thresholdValue}条，本次清理用户操作记录动作成功!");
                }
                else
                {
                    _logger.LogError($"【失败】当前的用户操作记录数量为{logTotalNum}条，用户操作记录已超设定值{thresholdValue}条，本次清理用户操作记录动作失败!");
                }
            }
        }
    }
}
